package top.xcxdl.rural.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import top.xcxdl.rural.common.Res;
import top.xcxdl.rural.entity.RuralUser;
import top.xcxdl.rural.service.IRuralUserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Ding
 * @since 2022-05-05
 */
@Api("后台管理用户控制器")
@RestController
@RequestMapping("/admin/user")
public class BackRuralUserController {

    @Resource
    private IRuralUserService service;

    /**
     * 后台获取用户列表
     *
     * @param pageNo   页码
     * @param pageSize 每页数量
     * @param key      搜索关键字
     * @return 用户列表
     */
    @GetMapping("/getList")
    @ResponseBody
    @ApiOperation("后台获取用户列表")
    public Res<Object> getList(
            @RequestParam(name = "page_no") Integer pageNo,
            @RequestParam(name = "page_size") Integer pageSize,
            @RequestParam(name = "title", required = false) String key
    ) {
        PageInfo<RuralUser> pageInfo = service.getList(pageNo, pageSize, key);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return Res.success(jsonObject);
    }

    /**
     * 后台修改用户状态
     *
     * @param user 用户实体
     * @return result
     */
    @ApiOperation("后台修改用户状态")
    @ResponseBody
    @PostMapping("/changeStatus")
    public Res<Object> changeStatus(@RequestBody RuralUser user) {
        return service.changeStatus(user) ? Res.success("操作成功") : Res.error("操作失败");
    }

    /**
     * 后台删除用户
     *
     * @param data{ ids: 用户id集合
     *              }
     * @return result
     */
    @ApiOperation("后台删除用户")
    @ResponseBody
    @PostMapping("/doDelete")
    public Res<Object> doDelete(@RequestBody JSONObject data) {
        //将json转为List<Integer>
        List<Integer> ids = (List<Integer>) data.get("ids");
        int ret = 0;
        ret += service.doDelete(ids);
        return ret == ids.size() ? Res.success("全部删除成功") : ret == 0 ? Res.error("操作失败") : Res.success("部分删除成功");
    }
}
